﻿Imports ISNet.WebUI.WebGrid
Imports System.Data
Imports System.DirectoryServices
Imports System.DirectoryServices.AccountManagement
Imports System.Security.Cryptography
Imports System.Text
Imports log4net
Imports log4net.Config

Partial Class CopyMaster
    Inherits System.Web.UI.Page

    Public AlertText As String
    Public ScriptText As String
    Dim logger As log4net.ILog = LogManager.GetLogger("Copy Master")

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If

        'Session("PlanYear") = "2557"
        If Page.IsPostBack = False Then
            FromYear.Text = Session("PlanYear")

        End If

        Label1.Text = "ระบบจัดทำงบประมาณ >> ตั้งค่าระบบ >> Copy Master"
    End Sub


    Protected Sub SaveBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SaveBtn.Click
        If Val(FromYear.Text) = 0 Or Val(ToYear.Text) = 0 Then
            Alert("กรุณาตรวจสอบปีที่จะทำการ Copy ข้อมูล")
            Exit Sub
        End If
        Dim b_adapter As New FundCenter2TableAdapters.BudgetDetailsTableAdapter
        Dim b_record As Integer
        ' Check Data จัดทำงบประมาณของปีแล้วหรือยัง By Year
        b_record = b_adapter.CheckData(Val(ToYear.Text))
        If b_record > 0 Then
            Alert("มีข้อมูลการจัดทำงบประมาณของปี " & ToYear.Text & " แล้ว ไม่สามารถทำการ Copy ข้อมูล Master ได้ ")
            Exit Sub
        End If
        '
        Dim check_adap As New CopyMasterDSTableAdapters.ExistTableAdapter
        Dim check_record As Integer
        check_record = check_adap.CountExist(Val(ToYear.Text))
        If check_record > 0 Then
            'Alert("มีข้อมูล Master ของปี " & ToYear.Text & " แล้วต้องการจะ delete ข้อมูล Master ทั้งหมดแล้วทำการ Copy ใหม่หรือไม่ ? ")
            ScriptText = "<script>Confirm();</script>"
            Exit Sub
        End If

        CopyProcess()

    End Sub

    Sub CopyProcess()
        'delete [userfundcenters]
        Dim uf_adapter As New CopyMasterDSTableAdapters.UserFundCentersTableAdapter
        uf_adapter.DeleteQuery(Val(ToYear.Text))
        'delete fund center hierarchy
        Dim h_adapter As New FundCenterParentTableAdapters.FundCenterHierarchiesTableAdapter
        h_adapter.DeleteByYear(Val(ToYear.Text))
        'delete  [FundCenterCmmts]
        Dim fc_adapter As New CopyMasterDSTableAdapters.FundCenterCmmtsTableAdapter
        fc_adapter.DeleteQuery(Val(ToYear.Text))
        'delete FundCenterTypeUser
        Dim ftu_adap As New CopyMasterDSTableAdapters.FundCenterTypeUserTableAdapter
        ftu_adap.DeleteQuery(Val(ToYear.Text))
        'delete FundCenterTypeCmmt
        Dim ftc_adap As New CopyMasterDSTableAdapters.FundCenterTypeCmmtTableAdapter
        ftc_adap.DeleteQuery(Val(ToYear.Text))
        'delete FundCenterType
        Dim fctype_adap As New CopyMasterDSTableAdapters.FundCenterTypeTableAdapter
        fctype_adap.DeleteQuery(Val(ToYear.Text))
        'delete Strategy
        Dim st_adap As New CopyMasterDSTableAdapters.StrategyTableAdapter
        st_adap.DeleteQuery(Val(ToYear.Text))
        'delete StrategyMapping
        Dim stm_adap As New CopyMasterDSTableAdapters.StrategyMappingTableAdapter
        stm_adap.DeleteQuery(Val(ToYear.Text))
        'delete Evm
        Dim evm_adap As New CopyMasterDSTableAdapters.EvmTableAdapter
        evm_adap.DeleteQuery(Val(ToYear.Text))
        'delete BusinessArea
        Dim bus_adap As New CopyMasterDSTableAdapters.BusinessAreaTableAdapter
        bus_adap.DeleteQuery(Val(ToYear.Text))
        'delete ProfitCenter
        Dim pro_adap As New CopyMasterDSTableAdapters.ProfitCenterTableAdapter
        pro_adap.DeleteQuery(Val(ToYear.Text))
        'delete ResponsibleAnalyst
        Dim resp_adap As New CopyMasterDSTableAdapters.ResponsibleAnalystTableAdapter
        resp_adap.DeleteQuery(Val(ToYear.Text))
        'delete fundcenter
        Dim f_adapter As New FundCenter2TableAdapters.FundCentersTableAdapter
        f_adapter.DeleteByYear(Val(ToYear.Text))
        'delete [[ProductItemRevs]]
        Dim pr_adapter As New CopyMasterDSTableAdapters.ProductItemRevsTableAdapter
        pr_adapter.DeleteQuery(Val(ToYear.Text))
        'delete [[CmmtDetails]]
        Dim cd_adapter As New CopyMasterDSTableAdapters.CmmtDetailsTableAdapter
        cd_adapter.DeleteQuery(Val(ToYear.Text))
        'delete [CmmtHierarchies]
        Dim ch_adapter As New CopyMasterDSTableAdapters.CmmtHierarchiesTableAdapter
        ch_adapter.DeleteQuery(Val(ToYear.Text))
        'delete [CmmtActivities]
        Dim ca_adap As New CopyMasterDSTableAdapters.CmmtActivitiesTableAdapter
        ca_adap.DeleteQuery(Val(ToYear.Text))
        'delete Cmmts
        Dim c_adapter As New CopyMasterDSTableAdapters.CmmtsTableAdapter
        c_adapter.DeleteQuery(Val(ToYear.Text))
        'delete activities
        Dim a_adapter As New CopyMasterDSTableAdapters.ActivitiesTableAdapter
        a_adapter.DeleteQuery(Val(ToYear.Text))
        'delete products
        Dim p_adapter As New CopyMasterDSTableAdapters.ProductsTableAdapter
        p_adapter.DeleteQuery(Val(ToYear.Text))
        'delete budget_version
        Dim bu_adapter As New CopyMasterDSTableAdapters.BudgetVersionsTableAdapter
        bu_adapter.DeleteQuery(Val(ToYear.Text))
        'delete activitytypes
        Dim ac_adapter As New CopyMasterDSTableAdapters.ActivityTypesTableAdapter
        ac_adapter.DeleteQuery(Val(ToYear.Text))
        'delete [funds]
        Dim fu_adapter As New CopyMasterDSTableAdapters.FundsTableAdapter
        fu_adapter.DeleteQuery(Val(ToYear.Text))
        'delete [ProductItems]
        Dim pi_adapter As New CopyMasterDSTableAdapters.ProductItemsTableAdapter
        pi_adapter.DeleteQuery(Val(ToYear.Text))
        'delete [costcenter]
        Dim cc_adapter As New CopyMasterDSTableAdapters.CostCentersTableAdapter
        cc_adapter.DeleteQuery(Val(ToYear.Text))
        'delete [BudgetControlType]
        Dim bct_adapter As New CopyMasterDSTableAdapters.BudgetControlTypeTableAdapter
        bct_adapter.DeleteQuery(Val(ToYear.Text))
        'delete [ProjectFundCenters]
        Dim pfc_adapter As New CopyMasterDSTableAdapters.ProjectFundCentersTableAdapter
        pfc_adapter.DeleteQuery(Val(ToYear.Text))
        'delete [UserFundCentersRP]
        'Dim ucr_adapter As New CopyMasterDSTableAdapters.UserFundCentersRPTableAdapter
        'ucr_adapter.DeleteQuery(Val(ToYear.Text))
        'Delete [CmmtFundCenters]
        Dim cfc_adapter As New CopyMasterDSTableAdapters.CmmtFundCentersTableAdapter
        cfc_adapter.DeleteQuery(Val(ToYear.Text))
        'delete [ActivityTypesFundcenter]
        Dim atf_adapter As New CopyMasterDSTableAdapters.ActivityTypesFundcenterTableAdapter
        atf_adapter.DeleteQuery(Val(ToYear.Text))
        
        'copy fund center type 
        fctype_adap.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy fund center type user
        ftu_adap.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy fund center type cmmt
        ftc_adap.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy strategy
        st_adap.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy strategy mapping
        stm_adap.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy evm
        evm_adap.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy business area
        bus_adap.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy profit center
        pro_adap.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy responsible analyst
        resp_adap.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy fund center 
        Dim f_datatable As New FundCenter2.FundCentersDataTable
        f_datatable = f_adapter.GetDataByyear(Val(FromYear.Text))
        Dim f_description As String

        For Each row As FundCenter2.FundCentersRow In f_datatable
            If row.IsDescriptionNull = True Then
                f_description = Nothing
            Else
                f_description = row.Description
            End If
            f_adapter.InsertQuery(row.FundCenterCode, Val(ToYear.Text), f_description, Nothing, Nothing, Nothing, Nothing)
        Next
        'copy fundcenterHierarchies
        Dim h_datatable As New FundCenterParent.FundCenterHierarchiesDataTable
        h_datatable = h_adapter.GetDataByOrgLevel(50, Val(FromYear.Text))
        Dim from_parent_id As Decimal = 0
        Dim parent_code As String = ""
        Dim parent_description As String = ""

        For Each row As FundCenterParent.FundCenterHierarchiesRow In h_datatable
            from_parent_id = row.Id
            parent_code = row.FundCenter_FundCenterCode
            If row.IsDescriptionNull = True Then
                parent_description = Nothing
            Else
                parent_description = row.Description
            End If
            Dim to_parent_id As Decimal
            to_parent_id = h_adapter.InsertQuery(Val(ToYear.Text), row.FundCenterGroup, row.Level, row.OrgLevel, parent_description, Nothing, Nothing, Nothing, Nothing, row.FundCenter_FundCenterCode, Val(ToYear.Text), Nothing, Nothing, Nothing)
            CopyByParent(from_parent_id, row.FundCenter_FundCenterCode, to_parent_id)
        Next
        'copy commitment
        c_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy activity
        a_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy [CmmtActivities]
        ca_adap.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy  [FundCenterCmmts]
        fc_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy products
        p_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy commitment detail
        cd_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy budget version
        bu_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))

        'users will not copy due to common use to all years
        'Dim u_adapter As New CopyMasterDSTableAdapters.UsersTableAdapter
        'u_adapter.DeleteQuery(Val(ToYear.Text))
        'u_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))

        'copy activity type
        ac_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy [CmmtHierarchies]
        Dim ch_datatable As New CopyMasterDS.CmmtHierarchiesDataTable
        ch_datatable = ch_adapter.GetDataByTop(Val(FromYear.Text))
        For Each row As CopyMasterDS.CmmtHierarchiesRow In ch_datatable
            Dim to_parent_id As Decimal
            Dim cmmtcode, description As String
            If row.IsCmmt_CmmtCodeNull = True Then
                cmmtcode = Nothing
            Else
                cmmtcode = row.Cmmt_CmmtCode
            End If
            If row.IsDescriptionNull = True Then
                description = Nothing
            Else
                description = row.Description
            End If
            to_parent_id = ch_adapter.InsertQuery(Val(ToYear.Text), row.CmmtGroup, row.Level, description, cmmtcode, Val(ToYear.Text), Nothing)
            CopyByParent_CH(row.Id, to_parent_id)
        Next
        'copy product item
        ''''pi_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))

        Dim batchadap As New MasschangeDSTableAdapters.BudgetDetailsTableAdapter
        Dim sqlall As String = ""

        Dim pi_dt As CopyMasterDS.ProductItemsDataTable
        pi_dt = pi_adapter.GetDataByYear(Val(FromYear.Text))
        Dim pid As Decimal
        For Each row As CopyMasterDS.ProductItemsRow In pi_dt
            pid = pi_adapter.InsertByID(Val(ToYear.Text), Val(FromYear.Text), row.Id)
            sqlall += BatchInsertPRev(row.Id, pid, Val(FromYear.Text), Val(ToYear.Text))
        Next
        Try
            batchadap.Execute(sqlall)
        Catch ex As Exception

        End Try

        'copy  [[ProductItemRevs]]
        pr_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy fund
        fu_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy cost center
        cc_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy userfundcenters
        uf_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy  [BudgetControlType]
        bct_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy  [ProjectFundCenters]
        pfc_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy  [UserFundCentersRP]
        'ucr_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy  [CmmtFundCenters]
        cfc_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))
        'copy  [ActivityTypesFundcenter]
        atf_adapter.InsertQuery(Val(ToYear.Text), Val(FromYear.Text))

        Alert("ทำการ Copy ข้อมูล Master เป็นที่เรียบร้อย")
    End Sub

    Sub CopyByParent_CH(ParentHierarchyID As Decimal, ToParentHierarchyID As Decimal)
        Dim ch_adapter As New CopyMasterDSTableAdapters.CmmtHierarchiesTableAdapter
        Dim ch_datatable As New CopyMasterDS.CmmtHierarchiesDataTable
        ch_datatable = ch_adapter.GetDataByParent(ParentHierarchyID)
        For Each row As CopyMasterDS.CmmtHierarchiesRow In ch_datatable
            Dim cmmtcode, description As String
            If row.IsCmmt_CmmtCodeNull = True Then
                cmmtcode = Nothing
            Else
                cmmtcode = row.Cmmt_CmmtCode
            End If
            If row.IsDescriptionNull = True Then
                description = Nothing
            Else
                description = row.Description
            End If
            Dim to_parent_id As Decimal
            to_parent_id = ch_adapter.InsertQuery(Val(ToYear.Text), row.CmmtGroup, row.Level, description, cmmtcode, Val(ToYear.Text), ToParentHierarchyID)
            CopyByParent_CH(row.Id, to_parent_id)
        Next

    End Sub

    Sub CopyByParent(ParentHierarchyID As Decimal, ParentFundcenterCode As String, ToParentHierarchyID As Decimal)
        Dim h_adapter As New FundCenterParentTableAdapters.FundCenterHierarchiesTableAdapter
        Dim h_datatable As New FundCenterParent.FundCenterHierarchiesDataTable
        h_datatable = h_adapter.GetDataByParentID(ParentHierarchyID)
        Dim description As String

        For Each row As FundCenterParent.FundCenterHierarchiesRow In h_datatable
            If row.IsDescriptionNull = True Then
                description = Nothing
            Else
                description = row.Description
            End If
            Dim to_parent_id As Decimal
            to_parent_id = h_adapter.InsertQuery(Val(ToYear.Text), row.FundCenterGroup, row.Level, row.OrgLevel, description, Nothing, Nothing, Nothing, Nothing, row.FundCenter_FundCenterCode, Val(ToYear.Text), ToParentHierarchyID, ParentFundcenterCode, Val(ToYear.Text))
            CopyByParent(row.Id, row.FundCenter_FundCenterCode, to_parent_id)
        Next

    End Sub

    Sub Alert(ByVal message As String)
        AlertText = "<script> alert('" & message & "');</script>"
    End Sub

    Protected Sub SaveConfirm_Click(sender As Object, e As EventArgs) Handles SaveConfirm.Click
        CopyProcess()
    End Sub

    Function BatchInsertPI(ByVal old_id As String, ByVal new_year As String) As String
        Dim sql As String = ""
        sql += " insert into [ProductItems] select "
        sql += " [ItemNo]"
        sql += " ," & new_year & " as [PlanYear]"
        sql += " ,[Description]"
        sql += " ,[ValueType]"
        sql += " ,[FormId]"
        sql += " ,null as [CreatedDate]"
        sql += " ,null as [UpdatedDate]"
        sql += " ,null as [CreatedBy]"
        sql += " ,null as [UpdatedBy]"
        sql += " from [ProductItems] where [Id] = " & old_id & ""


        sql += "; "

        Return sql
    End Function

    Function BatchInsertPRev(ByVal old_id As String, new_id As String, ByVal old_year As String, ByVal new_year As String) As String
        Dim sql As String = ""
        sql += " insert into [ProductItemRevs] select "
        sql += " " & new_year & " as [PlanYear]"
        sql += " ,[FormId]"
        sql += " ,null as [CreatedDate]"
        sql += " ,null as [UpdatedDate]"
        sql += " ,null as [CreatedBy]"
        sql += " ,null as [UpdatedBy]"
        sql += " ," & new_id & "as [ProductItem_Id]"
        sql += " ,[Cmmt_CmmtCode]"
        sql += " ," & new_year & " as [Cmmt_PlanYear]"
        sql += " ,[Product_ProductCode]"
        sql += " ," & new_year & " as [Product_PlanYear]"
        sql += " from [ProductItemRevs] where [PlanYear] = " & old_year & ""
        sql += " AND [ProductItem_Id] = " & old_id & ""

        sql += "; "

        Return sql
    End Function

End Class
